package com.atguigu.app.dws;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TrafficVideoPlayBean;
import com.atguigu.util.*;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName: edu-realtime
 * @Package: com.atguigu.gmall.app.dws
 * @ClassName DwsTrafficVideoPlayWindow
 * @Author jhh01
 * @Date 2022/9/3 21:24
 * @Description: ${测试代码}
 * @Version 1.0
 */
public class DwsTrafficVideoPlayWindow {
    public static void main(String[] args) throws Exception {
        //TODO 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //TODO 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(3 * 60 * 1000L);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");
        env.setStateBackend(new HashMapStateBackend());

         */


        // TODO 读取kafka dwd_traffic_video_play_detail主题的数据
        String topicName = "dwd_traffic_video_play_detail";
        String groupId = "dws_traffic_video_play_window";
//        {"user_id":"101","play_sec":"20","position_sec":"60","video_id":"1982","ts":1662209302603}

        DataStreamSource<String> videoStream = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));


        // TODO  转换为对应的javaBean
        SingleOutputStreamOperator<TrafficVideoPlayBean> beanStream = videoStream.map(new MapFunction<String, TrafficVideoPlayBean>() {
            @Override
            public TrafficVideoPlayBean map(String s) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                HashSet<String> hashSet = new HashSet<>();
                hashSet.add(jsonObject.getString("user_id"));
                TrafficVideoPlayBean trafficVideoPlayBean = TrafficVideoPlayBean.builder()
                        .videoId(jsonObject.getString("video_id"))
                        .videoplayedcount(1L)
                        .playedtimesum(Long.parseLong(jsonObject.getString("play_sec")))
                        .userIdset(hashSet)
                        .ts(Long.parseLong(jsonObject.getString("ts")) )
                        .build();


                return trafficVideoPlayBean;
            }
        });


//        beanStream.print("javabean>>>>>>>");
        // 和 DIM_VIDEO_INFO 关联
        SingleOutputStreamOperator<TrafficVideoPlayBean> joinStream = beanStream.map(new RichMapFunction<TrafficVideoPlayBean, TrafficVideoPlayBean>() {
            DruidDataSource dataSource = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                dataSource = DruidPhoenixDSUtil.getDataSource();
            }

            @Override
            public TrafficVideoPlayBean map(TrafficVideoPlayBean value) throws Exception {
                // select * from t where id = 'v.id'
                // 关联DIM_VIDEO_INFO商品表
                JSONObject dimVideoInfo= DimUtil.getDimInfo(dataSource.getConnection(), "DIM_VIDEO_INFO", value.getVideoId());

                if (dimVideoInfo!=null) {
                    value.setChapterId(dimVideoInfo.getString("chapterId"));

                }

                return value;

            }
        });

//        joinStream.print("chapter>>>>>>>>");
        SingleOutputStreamOperator<TrafficVideoPlayBean> beanwithwatermark = joinStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficVideoPlayBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<TrafficVideoPlayBean>() {
            @Override
            public long extractTimestamp(TrafficVideoPlayBean trafficVideoPlayBean, long l) {
                return trafficVideoPlayBean.getTs();
            }
        }));
        SingleOutputStreamOperator<TrafficVideoPlayBean> reduceStream = beanwithwatermark.keyBy(new KeySelector<TrafficVideoPlayBean, String>() {
            @Override
            public String getKey(TrafficVideoPlayBean trafficVideoPlayBean) throws Exception {
                return trafficVideoPlayBean.getChapterId() + trafficVideoPlayBean.getVideoId();
            }
        }).window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<TrafficVideoPlayBean>() {
                    @Override
                    public TrafficVideoPlayBean reduce(TrafficVideoPlayBean value1, TrafficVideoPlayBean value2) throws Exception {

                        Set<String> userIdset = value1.getUserIdset();
                        Set<String> userIdset1 = value2.getUserIdset();
                        userIdset.addAll(userIdset1);
                        value1.setVideoplayedcount(value1.getVideoplayedcount()+value2.getVideoplayedcount());
                        value1.setPersonwatchedcount((long) userIdset.size());
                        value1.setPlayedtimesum(value1.getPlayedtimesum() + value2.getPlayedtimesum());
                        if (value1.getPersonwatchedcount() != 0) {
                            value1.setAvgtime(value1.getPlayedtimesum()*1.0 / value1.getPersonwatchedcount());

                        }

                        return value1;
                    }
                }, new WindowFunction<TrafficVideoPlayBean, TrafficVideoPlayBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<TrafficVideoPlayBean> iterable, Collector<TrafficVideoPlayBean> out) throws Exception {
                        TrafficVideoPlayBean next = iterable.iterator().next();
                        next.setStt(DateFormatUtil.toYmdHms(timeWindow.getStart()));
                        next.setEdt(DateFormatUtil.toYmdHms(timeWindow.getEnd()));
                        next.setTs(System.currentTimeMillis());
                        out.collect(next);

                    }
                });
        reduceStream.print("reduce>>>>");

        reduceStream.addSink(MyClickHouseUtil.<TrafficVideoPlayBean>getSink("insert into dws_traffic_video_play_window values(?,?,?,?,?,?,?,?)"));


        env.execute(groupId);





    }
}
